package com.module.base.widget.skin;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.kyleduo.switchbutton.SwitchButton;
import com.module.base.R;

import skin.support.content.res.SkinCompatResources;
import skin.support.widget.SkinCompatHelper;
import skin.support.widget.SkinCompatSupportable;

/**
 * @author bsnl_yanxuwen
 * @date 2021/7/23 16:45
 * Description :
 * 换肤的SwitchButton
 */
public class SkinSwitchButton extends SwitchButton implements SkinCompatSupportable {
    private int INVALID_ID = 0;
    private int backDrawableId = INVALID_ID;

    public SkinSwitchButton(Context context) {
        this(context, null, 0);
    }

    public SkinSwitchButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SkinSwitchButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton, defStyle, 0);
        backDrawableId = a.getResourceId(R.styleable.SwitchButton_kswBackDrawable, INVALID_ID);
        a.recycle();
        applyBorderColorResource();
    }

    private void applyBorderColorResource() {
        try {
            backDrawableId = SkinCompatHelper.checkResourceId(backDrawableId);
            if (backDrawableId != INVALID_ID) {
                Drawable resId = SkinCompatResources.getDrawable(getContext(), backDrawableId);
                super.setBackDrawable(resId);
            } else {
                super.setBackDrawableRes(backDrawableId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setBackDrawableRes(int resId) {
        resId = SkinCompatHelper.checkResourceId(resId);
        if (resId != INVALID_ID) {
            Drawable drawable = SkinCompatResources.getDrawable(getContext(), resId);
            super.setBackDrawable(drawable);
        } else {
            super.setBackDrawableRes(resId);
        }
    }


    @Override
    public void applySkin() {
        applyBorderColorResource();
    }
}
